package com.leyou.item.service;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.leyou.common.pojo.PageResult;
import com.leyou.item.bo.SpuBo;
import com.leyou.item.mapper.*;
import com.leyou.item.pojo.*;
import org.apache.commons.lang.StringUtils;
import org.springframework.amqp.AmqpException;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import tk.mybatis.mapper.entity.Example;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class GoodsService {

    @Autowired
    private SpuMapper spuMapper;

    @Autowired
    private spuDetailMapper spuDetailMapper;

    @Autowired
    private  CategoryService categoryService;

    @Autowired
    private BrandMapper brandMapper;
    @Autowired
    private SkuMapper skuMapper;

    @Autowired
    private StockMapper stockMapper;

    @Autowired
    private AmqpTemplate amqpTemplate;

    public PageResult<SpuBo> querySpuBoByPage(String key,Boolean saleable, Integer page,Integer rows){
        Example example =new Example(Spu.class);
        Example.Criteria criteria = example.createCriteria();

        //判断搜索框,模糊查询
        if(org.apache.commons.lang.StringUtils.isNotBlank(key)){
            criteria.andLike("title","%"+key+"%");
        }

        //是否上架
        if(saleable!=null){
            criteria.andEqualTo("saleable", saleable);
        }

        // 添加分页条件
        PageHelper.startPage(page, rows);

        //执行查询
        List<Spu> spus = spuMapper.selectByExample(example);
        PageInfo<Spu> pageInfo =new PageInfo<>(spus);

        //把list<spu>转化为 list<spuBo>
        List<SpuBo> spuBos= new ArrayList<>();
        spus.forEach(spu -> {
            SpuBo spuBo = new SpuBo();
            // copy共同属性的值到新的对象
            BeanUtils.copyProperties(spu, spuBo);

            // 1。添加分类名称,三级分类
           List<String> names=  categoryService.queryNamesByIds(
                   Arrays.asList(spu.getCid1(), spu.getCid2(), spu.getCid3())
           ); //根据list集合查询分类名字

            spuBo.setCname(StringUtils.join(names, "/"));

            // 2.添加查询品牌的名称
            Brand brand = this.brandMapper.selectByPrimaryKey(spu.getBrandId());
            spuBo.setBname(brand.getName());
            spuBos.add(spuBo);

        });
        return new PageResult<>(pageInfo.getTotal(), spuBos);
    }

    //涉及4个表的插入，
    @Transactional
    public void saveGoods(SpuBo spuBo) {
        //1、spu表插入
        spuBo.setId(null);
        spuBo.setSaleable(true);
        spuBo.setValid(true);
        spuBo.setCreateTime(new Date());
        spuBo.setLastUpdateTime(spuBo.getCreateTime());
        spuMapper.insertSelective(spuBo);

        //2、插入  detail
        SpuDetail spuDetail = spuBo.getSpuDetail();
        spuDetail.setSpuId(spuBo.getId());
        this.spuDetailMapper.insertSelective(spuDetail);
        //调用方法
        saveSkuAndStock(spuBo);

        this.sendMsg("insert",spuBo.getId());
    }

    //新增sku和库存
    private void saveSkuAndStock(SpuBo spuBo) {
        spuBo.getSkus().forEach(sku -> {
            // 新增sku
            sku.setSpuId(spuBo.getId());
            sku.setCreateTime(new Date());
            sku.setLastUpdateTime(sku.getCreateTime());
            this.skuMapper.insertSelective(sku);

            // 新增库存
            Stock stock = new Stock();
            stock.setSkuId(sku.getId());
            stock.setStock(sku.getStock());
            this.stockMapper.insertSelective(stock);
        });
    }

    /**
     * 根据spuId查询spuDetail
     * @param spuId
     * @return
     */
    public SpuDetail querySpuDetailBySpuId(Long spuId) {
        return this.spuDetailMapper.selectByPrimaryKey(spuId);
    }

    /**
     * 根据spuId查询sku 和库存的集合
     * @param spuId
     * @return
     */
    public List<Sku> querySkusBySpuId(Long spuId) {
        Sku sku = new Sku();
        sku.setSpuId(spuId);
        List<Sku> skus = skuMapper.select(sku);
        //把库存也查出来
        skus.forEach(s -> {
            Stock stock = this.stockMapper.selectByPrimaryKey(s.getId());
            s.setStock(stock.getStock());
        });
        return skus;
    }

    //更新操作
    @Transactional
    public void updateGoods(SpuBo spuBo) {
        //先删除sku和库存两张表
        //先判断sku
        List<Sku> skus = this.querySkusBySpuId(spuBo.getId());
        if(!CollectionUtils.isEmpty(skus)){
            List<Long> ids = skus.stream().map(s -> s.getId()).collect(Collectors.toList());
            //如果有
            //根据skuID删除库存
            Example example = new Example(Stock.class);
            example.createCriteria().andIn("skuId", ids);
            this.stockMapper.deleteByExample(example);

            //根据spuID删除sku
            Sku sku = new Sku();
            sku.setSpuId(spuBo.getId());
            skuMapper.delete(sku);
        }

    // 新增sku和库存
        saveSkuAndStock(spuBo);

        // 更新spu
        spuBo.setLastUpdateTime(new Date());
        spuBo.setCreateTime(null);
        spuBo.setValid(null);
        spuBo.setSaleable(null);
        this.spuMapper.updateByPrimaryKeySelective(spuBo);

        // 更新spu详情
        this.spuDetailMapper.updateByPrimaryKeySelective(spuBo.getSpuDetail());

        this.sendMsg("update",spuBo.getId());

    }

    public Spu querySpuById(Long spuId) {
        return this.spuMapper.selectByPrimaryKey(spuId);
    }

    //发送消息
    private void sendMsg(String type,Long spuId){
        try {
            this.amqpTemplate.convertAndSend("item." + type, spuId);
        }catch (AmqpException e){
            e.printStackTrace();
        }
    }
}
